import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserPost } from './entities/user-post.entity';
import { In, Repository } from 'typeorm';

@Injectable()
export class UserPostService {
  constructor(
    @InjectRepository(UserPost) private readonly userPostRepository: Repository<UserPost>,
  ) {}

  /**
   * 根据用户id获取岗位id
   * @param userId 
   * @returns 
   */
 async getPostIdByUserId(userId: number) {
   const userPost = await this.userPostRepository.find({
     where: { user_id: userId },
   });
   return userPost.map((userPost) => userPost.post_id);
 }

  /**
   * 修改用户岗位关联（新增、修改、删除）
   * @param id 用户id
   * @param postIds 岗位id数组
   */
  async updateUserPost(id: number, postIds: number[]) {
    try {
      return await this.userPostRepository.manager.transaction(
        async (manager) => {
          // 查找表中的用户角色
          const userPosts = await manager.find(UserPost, {
            where: {
              user_id: id,
            },
          });
          // 在postIds中找出不在userPosts中的角色id，新增表中没有的用户角色
          let insertRows = postIds.filter(
            (k) => !userPosts.some((j) => j.user_id == id && j.post_id == k),
          );
          if (insertRows && insertRows.length > 0) {
            await manager.insert(
              UserPost,
              insertRows.map((k) => {
                return {
                  user_id: id,
                  post_id: k,
                };
              }),
            );
          }

          // 在userPosts中找出postIds所没有的，删除表中没有userPosts的用户角色
          let deleteRows = userPosts.filter(
            (k) => !postIds.some((j) => j == k.post_id),
          );
          if (deleteRows && deleteRows.length > 0) {
            await manager.delete(UserPost, {
              user_id: id,
              post_id: In(deleteRows.map((k) => k.post_id)),
            });
          }
        },
      );
    } catch (err) {
      return err;
    }
  }
}
